package com.uzai.console.service.alipaymch.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundBatchCreateRequest;
import com.alipay.api.request.AlipayFundBatchDetailQueryRequest;
import com.alipay.api.request.AlipayFundTransPagePayRequest;
import com.alipay.api.response.AlipayFundBatchCreateResponse;
import com.alipay.api.response.AlipayFundBatchDetailQueryResponse;
import com.alipay.api.response.AlipayFundTransPagePayResponse;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.Math;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.Const;
import com.uzai.console.dto.alipaymchbatch.AlipayBatchPayDto;
import com.uzai.console.service.alipaymch.AlipayFundBatchService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.*;


/**
 * @Auther: jianghan
 * @Date: 2021/12/15 20:12
 * @Description:
 */
@Service
public class AlipayFundBatchServiceImpl implements AlipayFundBatchService {

    private static Logger logger = LoggerFactory.getLogger(AlipayFundBatchServiceImpl.class);

    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;

    @Override
    public AlipayFundBatchCreateResponse create(String authToken, AlipayBatchPayDto alipayBatchPayDto) {
        AlipayFundBatchCreateResponse response = null;
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(uzaiConsoleSysConfig.getAlipayGateway(),
                    uzaiConsoleSysConfig.getAlipayPartnerAppId(), uzaiConsoleSysConfig.getAlipayPartnerAppPrivateKey(),
                    uzaiConsoleSysConfig.getAlipayFormat(), uzaiConsoleSysConfig.getAlipayCharset(),
                    uzaiConsoleSysConfig.getAlipayPartnerPublicKey(), uzaiConsoleSysConfig.getAlipaySignType());

            AlipayFundBatchCreateRequest request = new AlipayFundBatchCreateRequest();

            Map<String,Object> params = new HashMap<>();
            params.put("out_batch_no", alipayBatchPayDto.getBatchNo());
            params.put("product_code","BATCH_API_TO_ACC");
            params.put("biz_scene","MESSAGE_BATCH_PAY");
            params.put("order_title", alipayBatchPayDto.getPayTitle());
            params.put("remark", alipayBatchPayDto.getPayDesc());
            //支付绝对超时时间，格式为yyyy-MM-dd HH:mm
            Date now = new Date();
            long time = Const.AlipayMchBatch.effective_time * 60 * 1000; //30分钟
            Date afterDate = new Date(now.getTime() + time);//30分钟后的时间
            String time_expire = Tools.getDateFormat(afterDate, "yyyy-MM-dd HH:mm");
            params.put("time_expire", time_expire);
            List<AlipayBatchPayDto.PayDetail> list = alipayBatchPayDto.getPayDetails();
            List<Map> payDetails = new ArrayList<>();
            double totalAmount = 0d;
            for (AlipayBatchPayDto.PayDetail detail:list){
                Map<String,Object> detailMap = new HashMap<>();
                detailMap.put("out_biz_no", detail.getTradeNo());
                detailMap.put("trans_amount", String.valueOf(detail.getAmount()));
                detailMap.put("order_title", alipayBatchPayDto.getPayTitle());
                detailMap.put("remark", alipayBatchPayDto.getPayDesc());
                //收款方信息
                Map<String ,Object> payeeInfo = new HashMap<>();
                payeeInfo.put("identity", detail.getAlipayAccount());
                payeeInfo.put("identity_type", "ALIPAY_LOGON_ID");
                payeeInfo.put("name", detail.getAlipayName());
                detailMap.put("payee_info", payeeInfo);
                payDetails.add(detailMap);
                totalAmount = Math.add(totalAmount, detail.getAmount());
            }
            if(totalAmount != alipayBatchPayDto.getTotalAmount()){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "转账总金额有误");
            }
            params.put("total_trans_amount", totalAmount);
            params.put("total_count",payDetails.size());
            params.put("trans_order_list", payDetails);

            String paramStr = JSONObject.toJSONString(params);
            logger.info("alipay batch create req:{}",paramStr);
            request.setBizContent(paramStr);
            request.putOtherTextParam("app_auth_token", authToken);
            response = alipayClient.execute(request);
            logger.info("alipay batch create resp:{}",response.getBody());
        } catch (Exception e) {
            logger.error("err:",e);
        }
        return response;
    }

    @Override
    public AlipayFundTransPagePayResponse pay(String authToken, String batchTransId) {

        try {
            if (StringUtils.isBlank(batchTransId)){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "批量转账订单号为空");
            }
            AlipayClient alipayClient = new DefaultAlipayClient(uzaiConsoleSysConfig.getAlipayGateway(),
                    uzaiConsoleSysConfig.getAlipayPartnerAppId(),uzaiConsoleSysConfig.getAlipayPartnerAppPrivateKey(),
                    uzaiConsoleSysConfig.getAlipayFormat(),uzaiConsoleSysConfig.getAlipayCharset(),uzaiConsoleSysConfig.getAlipayPartnerPublicKey(),uzaiConsoleSysConfig.getAlipaySignType());
            AlipayFundTransPagePayRequest request = new AlipayFundTransPagePayRequest();
            Map<String ,Object> param = new HashMap<>();
            param.put("biz_scene","MESSAGE_BATCH_PAY");
            param.put("product_code","BATCH_API_TO_ACC");
            param.put("order_id",batchTransId);

            //支付绝对超时时间，格式为yyyy-MM-dd HH:mm
            Date now = new Date();
            long time = Const.AlipayMchBatch.effective_time * 60 * 1000;   //30分钟
            Date afterDate = new Date(now.getTime() + time);//30分钟后的时间
            String time_expire = Tools.getDateFormat(afterDate, "yyyy-MM-dd HH:mm");
            param.put("time_expire", time_expire);
            String paramStr = JSONObject.toJSONString(param);
            logger.info("alipay batch pay req:{}",paramStr);
            request.setBizContent(paramStr);
            request.putOtherTextParam("app_auth_token",authToken);
            AlipayFundTransPagePayResponse response = alipayClient.pageExecute(request, "GET");
            logger.info("alipay batch pay resp:{}",response.getBody());
            return response;
        } catch (Exception e) {
            logger.error("err:",e);
        }
        return null;
    }

    @Override
    public AlipayFundBatchDetailQueryResponse query(String batchNo, String appAuthToken) {
        try {
            if (StringUtils.isBlank(batchNo)){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "批量转账订单号为空");
            }
            AlipayClient alipayClient = new DefaultAlipayClient(uzaiConsoleSysConfig.getAlipayGateway(),
                    uzaiConsoleSysConfig.getAlipayPartnerAppId(),uzaiConsoleSysConfig.getAlipayPartnerAppPrivateKey(),
                    uzaiConsoleSysConfig.getAlipayFormat(),uzaiConsoleSysConfig.getAlipayCharset(),uzaiConsoleSysConfig.getAlipayPartnerPublicKey(),uzaiConsoleSysConfig.getAlipaySignType());
            AlipayFundBatchDetailQueryRequest request = new AlipayFundBatchDetailQueryRequest();
            Map<String ,Object> param = new HashMap<>();
            param.put("out_batch_no", batchNo);
            param.put("biz_scene", "MESSAGE_BATCH_PAY");
            param.put("product_code", "BATCH_API_TO_ACC");
            String paramStr = JSONObject.toJSONString(param);
            logger.info("alipay batch pay req:{}",paramStr);
            request.setBizContent(paramStr);
            request.putOtherTextParam("app_auth_token",appAuthToken);
            AlipayFundBatchDetailQueryResponse response = alipayClient.execute(request, "GET");
            logger.info("alipay batch pay resp:{}",response.getBody());
            return response;
        } catch (Exception e) {
            logger.error("err:",e);
        }
        return null;
    }
}
